package cn.ac.cintcm.webapp.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cn.ac.cintcm.Constants;
import cn.ac.cintcm.model.Therapy;
import cn.ac.cintcm.model.User;
import cn.ac.cintcm.service.TherapyManager;
import cn.ac.cintcm.service.UserManager;

public class UserVisitController extends MultiActionController {
	private final Log log = LogFactory.getLog(UserVisitController.class);
	private UserManager mgr = null;
	private TherapyManager tm = null;
	
	public void setUserManager(UserManager userManager) {
	    this.mgr = userManager;
	}
	
	public void setTherapyManager(TherapyManager tm) {
		this.tm = tm;
	}
	
	public ModelAndView usercare(HttpServletRequest request,
	                                  HttpServletResponse response)
	throws Exception {
		String username = request.getRemoteUser();
	    return new ModelAndView("usercare", Constants.USER_LIST, mgr.getAttentionUser(username));
	}

	
	public ModelAndView notified(HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {
		String u = request.getParameter("u");
		String username =  request.getRemoteUser();

		if (u != null && !u.equals("")) {
			User user = mgr.getUserByUsername(u);
			log.debug("entering notification:username" + u + "Id:" +user.getId() );
			Therapy therapy = tm.getUnnotifiedTherapy(user.getId());
			therapy.setNotify(true);
			tm.save(therapy);
		}
		return new ModelAndView("usercare", Constants.USER_LIST, mgr.getAttentionUser(username));
	}
	

	public ModelAndView search(HttpServletRequest request,
            HttpServletResponse response)
						throws Exception {
		String key = request.getParameter("key");
		String username = request.getRemoteUser();
		List<User> users = null;
		if (key != null && !key.trim().equals("")) {
			if (request.isUserInRole(Constants.ADMIN_ROLE)) {
				users = mgr.search(key, null);
			} else {
				users = mgr.search(key, username);
			}
			return new ModelAndView("admin/userList", Constants.USER_LIST, users);
		} else {
			return new ModelAndView("admin/userList", Constants.USER_LIST, mgr.getRecentUser(username));
		}
	}
	
	public ModelAndView checknewdoctors(HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {

		return new ModelAndView("admin/userList", Constants.USER_LIST, mgr.getNewDoctors());

	}
}
